package recursion;

import java.util.Scanner;

//斐波那契数
public class FibonacciNumber2 {
    public static void main(String[] args) {
        while (true) {
            System.out.println("输入整数n,求第n个斐波那契数");
            int n = new Scanner(System.in).nextInt();
            long result = f(n);
            //System.out.printf("第%d个斐波那契数是: %d\n", n, result);
            System.out.println(result);
        }
    }

    private static long f(int n) {
        if (n < 1) { //特殊情况
            return 0;
        }
        if (n == 1 || n == 2) { //最简问题
            return 1;
        }
        int a = 1;
        int b = 1;
        for (int i = 3; i <= n; i++) {
            b = a + b; //第n-1个数
            a = b - a; //第n-2个数
        }
        return b;
    }
}
